﻿Imports Microsoft.VisualBasic
Imports System.Data.OleDb

Public Class BattleshipGameControl
    Event UpdateTextOutput(ByRef playerfeedback As String)
    Event OutputGridToDraw(ByVal TypeOfGridToDraw As Integer, ByVal GridToDraw As BattleshipGameGrid, ByVal shipforlayergrid As Ship)
    Event EnableInteractivity()
    Event DisableInteractivity()
    Event DisableShipPlacementUI()
    Event HotSeatBlackOut()
    Event EndGameEvent()
    Event ClearPB()
    Event SetNames()
    Dim computerShips As New Queue
    Private m_CurrentGame As BattleshipGame

    Property CurrentGame As BattleshipGame
        Get
            Return m_CurrentGame
        End Get
        Set(ByVal value As BattleshipGame)
            m_CurrentGame = value
        End Set
    End Property
    'This event is practically the whole application.
    Function HandleClickEvent(ByVal col As Integer, ByVal row As Integer, ByVal gridclicked As Integer, ByVal verticalorhorizontal As Integer) As Boolean

        If CurrentGame.CurrentPhase = 1 Then

            'It is phase 1, the ship placement phase.

            If CurrentGame.CurrentPlayerTurn = 1 Then
                If gridclicked = 1 Then
                    If CurrentGame.Player1_ShipstoPlace > 0 Then
                        If CheckIfEligibleForShipPlacement(col, row, CurrentGame.Player1_Ships(CurrentGame.Player1_ShipstoPlace).Size, verticalorhorizontal, CurrentGame.Player1TrackingGrid) = True Then
                            PlaceShip(col, row, CurrentGame.Player1_Ships(CurrentGame.Player1_ShipstoPlace), verticalorhorizontal, CurrentGame.Player1TrackingGrid)
                            CurrentGame.Player1_ShipstoPlace -= 1 'The ship is placed, and there's one less to place now.
                            If CurrentGame.Player1_ShipstoPlace = 0 Then 'If that was the last one, blow out of the first player's placement phase.
                                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing) 'Form1.DrawAGrid(1, CurrentGame.Player1TrackingGrid)
                                Me.ManageTurnsAndPhases(11) 'I use integers because strings are just as undecipherable
                                Return True 'This is kinda cheaty, i didn't want the click event to presist and set the second player's first ship. Also, I didn't need the ui to re-draw because it's player 2's turn now.
                            End If
                            If CurrentGame.Player1_ShipstoPlace > 0 Then 'if there is more ships, the game tells the player what the next ship is and waits for another click event.
                                RaiseEvent UpdateTextOutput("Player " + CurrentGame.CurrentPlayerTurn.ToString + ": " + "Place Your " + CurrentGame.Player1_Ships(CurrentGame.Player1_ShipstoPlace).Name.ToString)
                                RaiseEvent OutputGridToDraw(3, Nothing, CurrentGame.Player1_Ships(CurrentGame.Player1_ShipstoPlace))
                            End If
                            RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing) 'Form1.DrawAGrid(1, CurrentGame.Player1TrackingGrid)
                        Else
                            MessageBox.Show("Invalid Placement")
                        End If
                    Else
                        MessageBox.Show("You can only place ships at this time!")
                    End If
                End If
            End If


            If CurrentGame.CurrentPlayerTurn = 2 Then
                If CurrentGame.NumPlayers = 2 Then
                    If gridclicked = 1 Then
                        If CurrentGame.Player2_ShipstoPlace > 0 Then
                            If CheckIfEligibleForShipPlacement(col, row, CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Size, verticalorhorizontal, CurrentGame.Player2TrackingGrid) = True Then
                                PlaceShip(col, row, CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace), verticalorhorizontal, CurrentGame.Player2TrackingGrid)
                                CurrentGame.Player2_ShipstoPlace -= 1 'The ship is placed, and there's one less to place now.
                                If CurrentGame.Player2_ShipstoPlace = 0 Then 'If that was the last one, blow out of the first player's placement phase.
                                    RaiseEvent OutputGridToDraw(1, CurrentGame.Player2TrackingGrid, Nothing)
                                    Me.ManageTurnsAndPhases(22) 'I use integers because strings are just as undecipherable
                                    Return True 'This is kinda cheaty, i didn't want the click event to presist and set the second player's first ship. Also, I didn't need the ui to re-draw because it's player 2's turn now.
                                End If
                                If CurrentGame.Player2_ShipstoPlace > 0 Then 'if there is more ships, the game tells the player what the next ship is and waits for another click event.
                                    RaiseEvent UpdateTextOutput("Player " + CurrentGame.CurrentPlayerTurn.ToString + ": " + "Place Your " + CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name.ToString)
                                    RaiseEvent OutputGridToDraw(3, Nothing, CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace))
                                End If
                                RaiseEvent OutputGridToDraw(1, CurrentGame.Player2TrackingGrid, Nothing) 'Form1.DrawAGrid(1, CurrentGame.Player1TrackingGrid)
                            Else
                                MessageBox.Show("Invalid Placement")
                            End If
                        Else
                            MessageBox.Show("You can only place ships at this time!")
                        End If
                    End If
                ElseIf CurrentGame.NumPlayers = 1 Then
                    Dim x As Integer
                    Dim y As Integer
                    x = computerShips.Dequeue()
                    y = computerShips.Dequeue()
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 1, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 2, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 3, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 4, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2_ShipstoPlace -= 1
                    x = computerShips.Dequeue()
                    y = computerShips.Dequeue()
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 1, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 2, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 3, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2_ShipstoPlace -= 1
                    x = computerShips.Dequeue()
                    y = computerShips.Dequeue()
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 1, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 2, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2_ShipstoPlace -= 1
                    x = computerShips.Dequeue()
                    y = computerShips.Dequeue()
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 1, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 2, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2_ShipstoPlace -= 1
                    x = computerShips.Dequeue()
                    y = computerShips.Dequeue()
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2TrackingGrid.PlayerGrid(x + 1, y).ShipName = CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name
                    CurrentGame.Player2_ShipstoPlace -= 1
                    Me.ManageTurnsAndPhases(23)
                End If
            End If 'end player2 phase 1 events

        End If 'end checking for phase 1 conditions

        'begin phase 2: the actual game
        If CurrentGame.CurrentPhase = 2 Then
            If gridclicked = 1 Then
                MessageBox.Show("You should fire on the enemy's ships, Captain!")
                Return False
            End If

            If Shot(col, row) = False Then
                MessageBox.Show("You have already fired here. Try again.")
            Else
                Shot(col, row)
                If CurrentGame.NumPlayers = 2 Then
                    If CurrentGame.CurrentPlayerTurn = 1 Then
                        Me.ManageTurnsAndPhases(31)
                        Return True
                    End If
                    If gridclicked = 2 Then
                        Shot(col, row)
                    End If

                    If CurrentGame.CurrentPlayerTurn = 2 Then
                        Me.ManageTurnsAndPhases(32)
                        Return True

                    End If
                End If

                If CurrentGame.NumPlayers = 1 Then
                    Me.ManageTurnsAndPhases(41)
                    Me.ManageTurnsAndPhases(42)
                    Return True
                End If
            End If
            'Return False
        End If


        Return False
    End Function
    Function PlaceShip(ByVal col As Integer, ByVal row As Integer, ByRef shiptodrop As Ship, ByVal horizontalvertical As Integer, ByRef gridtoplace As BattleshipGameGrid)

        If horizontalvertical = 1 Then
            For i = 0 To (shiptodrop.Size - 1) Step 1
                gridtoplace.PlayerGrid(col + i, row).ShipExists = True
                gridtoplace.PlayerGrid(col + i, row).ShipSprite = shiptodrop.HorizontalSprites(i + 1)
                gridtoplace.PlayerGrid(col + i, row).ShipName = shiptodrop.Name
            Next
            Return True
        End If


        If horizontalvertical = 2 Then
            For i = 0 To (shiptodrop.Size - 1) Step 1
                gridtoplace.PlayerGrid(col, row + i).ShipExists = True
                gridtoplace.PlayerGrid(col, row + i).ShipSprite = shiptodrop.VerticalSprites(i + 1)
                gridtoplace.PlayerGrid(col, row + i).ShipName = shiptodrop.Name
            Next
            Return True
        End If


        Return False
    End Function
    Function CheckIfEligibleForShipPlacement(ByVal col As Integer, ByVal row As Integer, ByVal shipsizetocheck As Integer, ByVal horizontalorvertical As Integer, ByRef gridtocheck As BattleshipGameGrid) As Boolean

        Dim gridsize As Integer = 10


        'first, we determine if there is enough space to fit the whole ship in on the grid.

        If horizontalorvertical = 1 Then 'Check for horizontal placement

            If shipsizetocheck + col > gridsize + 1 Then
                '   MessageBox.Show("A ship won't fit there")
                Return False
            Else
                For k As Integer = 0 To (shipsizetocheck - 1) Step 1
                    '  MessageBox.Show("Inside the is there a fucking boat here: " + (col + k).ToString + "," + row.ToString + "isthereashiphere? " + gridtocheck.PlayerGrid((col + k), row).ShipExists.ToString)
                    If gridtocheck.PlayerGrid((col + k), row).ShipExists = True Then
                        ' MessageBox.Show("there is already a fucking boat there")
                        Return False
                    End If
                Next

            End If
            Return True
        End If



        If horizontalorvertical = 2 Then 'Check for horizontal placement

            If shipsizetocheck + row > gridsize + 1 Then
                MessageBox.Show("A ship won't fit there")
                Return False
            Else
                For k As Integer = 0 To (shipsizetocheck - 1) Step 1
                    '  MessageBox.Show("Inside the is there a fucking boat here: " + (col + k).ToString + "," + row.ToString + "isthereashiphere? " + gridtocheck.PlayerGrid((col + k), row).ShipExists.ToString)
                    If gridtocheck.PlayerGrid(col, (row + k)).ShipExists = True Then
                        ' MessageBox.Show("there is already a fucking boat there")
                        Return False
                    End If
                Next

            End If
            Return True
        End If

        Return False

    End Function
    'the actual shot method, for phase 2.
    Public Function Shot(ByVal x As Integer, ByVal y As Integer) As Boolean


        If CurrentGame.CurrentPlayerTurn = 1 Then
            If CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipExists = True Then
                If CurrentGame.Player1FiringGrid.PlayerGrid(x, y).ShotState = 2 Then
                    Return False
                    Exit Function
                End If
                RaiseEvent UpdateTextOutput("Player One shot Player Two's " + CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName)
                MessageBox.Show("You hit Player Two's " + CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipName + "!")
                CurrentGame.Player2Lives -= 1
                CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShotState = 2
                CurrentGame.Player1FiringGrid.PlayerGrid(x, y).ShotState = 2
                If CurrentGame.CheckWinConditions() = True Then
                    Me.GameOver()
                End If
                Return True
            End If

            If CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShipExists = False Then
                If CurrentGame.Player1FiringGrid.PlayerGrid(x, y).ShotState = 1 Then
                    Return False
                    Exit Function
                End If
                MessageBox.Show("You missed!")
                CurrentGame.Player2TrackingGrid.PlayerGrid(x, y).ShotState = 1
                CurrentGame.Player1FiringGrid.PlayerGrid(x, y).ShotState = 1
                Return True
            End If
        End If

        If CurrentGame.CurrentPlayerTurn = 2 Then
            If CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShipExists = True Then
                If CurrentGame.Player2FiringGrid.PlayerGrid(x, y).ShotState = 2 Then
                    Return False
                    Exit Function
                End If
                RaiseEvent UpdateTextOutput("Player Two shot Player One's " + CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShipName.ToString)
                If CurrentGame.NumPlayers = 2 Then
                    MessageBox.Show("You hit Player One's " + CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShipName + "!")
                ElseIf CurrentGame.NumPlayers = 1 Then
                    MessageBox.Show("Player Two hit your " + CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShipName + "!")
                End If
                CurrentGame.Player1Lives -= 1
                CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShotState = 2
                CurrentGame.Player2FiringGrid.PlayerGrid(x, y).ShotState = 2
                If CurrentGame.CheckWinConditions() = True Then
                    Me.GameOver()
                    MsgBox("Game is officially over.")
                End If
                Return True
            End If

            If CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShipExists = False Then
                If CurrentGame.Player2FiringGrid.PlayerGrid(x, y).ShotState = 1 Then
                    Return False
                    Exit Function
                End If
                If CurrentGame.NumPlayers = 2 Then
                    MessageBox.Show("You missed!")

                ElseIf CurrentGame.NumPlayers = 1 Then
                    MessageBox.Show("Player Two missed!")
                End If

                CurrentGame.Player1TrackingGrid.PlayerGrid(x, y).ShotState = 1
                CurrentGame.Player2FiringGrid.PlayerGrid(x, y).ShotState = 1
                Return True
            End If
        End If

        Return Nothing
    End Function
    Sub New()
        m_CurrentGame = Nothing
        Me.CurrentGame = Nothing
        Me.CurrentGame = New BattleshipGame
    End Sub
    Public Sub ManageTurnsAndPhases(ByVal gameconditioncode As Integer)

        Select Case gameconditioncode

            Case 0 'The game needs to be initialized
                CurrentGame.CurrentPhase = 1
                CurrentGame.CurrentPlayerTurn = 1

                RaiseEvent ClearPB()
                RaiseEvent EnableInteractivity()
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(3, Nothing, CurrentGame.Player1_Ships(CurrentGame.Player1_ShipstoPlace))
                
            Case 11 'Player 1 is done placing ships
                RaiseEvent UpdateTextOutput("Player One's Ships Are Placed")
                CurrentGame.CurrentPlayerTurn = 2
                If CurrentGame.NumPlayers = 2 Then
                    RaiseEvent HotSeatBlackOut()
                    RaiseEvent OutputGridToDraw(1, CurrentGame.Player2TrackingGrid, Nothing)
                    RaiseEvent OutputGridToDraw(3, Nothing, CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace))
                    RaiseEvent UpdateTextOutput("Player " + CurrentGame.CurrentPlayerTurn.ToString + ": " + "Place Your " + CurrentGame.Player2_Ships(CurrentGame.Player2_ShipstoPlace).Name.ToString)
                ElseIf CurrentGame.NumPlayers = 1 Then
                    CreateComputerPlayer()
                    RaiseEvent UpdateTextOutput("Computer player has placed his ships.")
                    RaiseEvent UpdateTextOutput("Player One, click on your Firing Grid to Attack!")
                Else
                    MsgBox("Invalid number of players!")
                End If

            Case 22 ' Player 2 is done placing ships, and now we set up battleship for reals.
                RaiseEvent UpdateTextOutput("clear")
                RaiseEvent DisableShipPlacementUI()
                CurrentGame.CurrentPhase = 2
                RaiseEvent HotSeatBlackOut()
                CurrentGame.CurrentPlayerTurn = 1
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player1FiringGrid, Nothing)
                RaiseEvent UpdateTextOutput("Player Two's Ships Are Placed")
                RaiseEvent UpdateTextOutput("Player One, click on your Firing Grid to Attack!")

            Case 23 ' Player 2 is a computer player, setting up battleship for this case
                RaiseEvent UpdateTextOutput("clear")
                RaiseEvent DisableShipPlacementUI()
                CurrentGame.CurrentPhase = 2
                CurrentGame.CurrentPlayerTurn = 1
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player1FiringGrid, Nothing)
                RaiseEvent UpdateTextOutput("Player Two's Ships Are Placed")
                RaiseEvent UpdateTextOutput("Player One, click on your Firing Grid to Attack!")

            Case 31 ' Player 1 is done shooting, and hasn't won
                RaiseEvent HotSeatBlackOut()
                CurrentGame.CurrentPlayerTurn = 2
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player2TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player2FiringGrid, Nothing)

            Case 32 ' Player 2 is done shooting, and hasn't won
                RaiseEvent HotSeatBlackOut()
                CurrentGame.CurrentPlayerTurn = 1
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player1FiringGrid, Nothing)

            Case 41 'Player 1 is done shooting and hasn't won
                CurrentGame.CurrentPlayerTurn = 2
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player1FiringGrid, Nothing)

            Case 42 'Computer player is done shooting and hasn't won
                ComputerTurn()
                CurrentGame.CurrentPlayerTurn = 1
                RaiseEvent OutputGridToDraw(1, CurrentGame.Player1TrackingGrid, Nothing)
                RaiseEvent OutputGridToDraw(2, CurrentGame.Player1FiringGrid, Nothing)
        End Select
    End Sub
    Public Sub CreateComputerPlayer()
        CurrentGame.Player2Name = "Computer"
        Dim ShipsLeft As Integer = 5
        Dim finished As Boolean = False
        Randomize()
        Dim xValue As Integer = CInt(Int((6 * Rnd()) + 1))
        Dim yValue As Integer = CInt(Int((10 * Rnd()) + 1))
        computerShips.Enqueue(xValue)
        computerShips.Enqueue(yValue)
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 3, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 4, yValue).ShipExists = True

        Do While finished = False
            xValue = CInt(Int((7 * Rnd()) + 1))
            yValue = CInt(Int((10 * Rnd()) + 1))
            If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True Then
                Continue Do
            Else
                If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True Then
                    Continue Do
                Else
                    If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True Then
                        Continue Do
                    Else
                        If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 3, yValue).ShipExists = True Then
                            Continue Do
                        Else
                            finished = True
                            computerShips.Enqueue(xValue)
                            computerShips.Enqueue(yValue)
                            Exit Do
                        End If
                    End If
                End If
            End If
        Loop
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 3, yValue).ShipExists = True
        finished = False

        Do While finished = False
            xValue = CInt(Int((8 * Rnd()) + 1))
            yValue = CInt(Int((10 * Rnd()) + 1))
            If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True Then
                Continue Do
            Else
                If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True Then
                    Continue Do
                Else
                    If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True Then
                        Continue Do
                    Else
                        finished = True
                        computerShips.Enqueue(xValue)
                        computerShips.Enqueue(yValue)
                        Exit Do
                    End If
                End If
            End If
        Loop

        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True
        finished = False

        Do While finished = False
            xValue = CInt(Int((8 * Rnd()) + 1))
            yValue = CInt(Int((10 * Rnd()) + 1))
            If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True Then
                Continue Do
            Else
                If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True Then
                    Continue Do
                Else
                    If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True Then
                        Continue Do
                    Else
                        computerShips.Enqueue(xValue)
                        computerShips.Enqueue(yValue)
                        finished = True
                        Exit Do
                    End If
                End If
            End If
        Loop

        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 2, yValue).ShipExists = True
        finished = False

        Do While finished = False
            xValue = CInt(Int((9 * Rnd()) + 1))
            yValue = CInt(Int((10 * Rnd()) + 1))
            If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True Then
                Continue Do
            Else
                If CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True Then
                    Continue Do
                Else
                    computerShips.Enqueue(xValue)
                    computerShips.Enqueue(yValue)
                    finished = True
                    Exit Do
                End If
            End If
        Loop
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue, yValue).ShipExists = True
        CurrentGame.Player2TrackingGrid.PlayerGrid(xValue + 1, yValue).ShipExists = True
    End Sub
    Public Sub ComputerTurn()
        Randomize()
        Dim finished As Boolean = False
        Do While finished = False
            Dim xValue As Integer = CInt(Int((10 * Rnd()) + 1))
            Dim yValue As Integer = CInt(Int((10 * Rnd()) + 1))
            If CurrentGame.Player1TrackingGrid.PlayerGrid(xValue, yValue).ShotState = 0 Then
                Me.Shot(xValue, yValue)
                finished = True
                Exit Do
            Else
                Continue Do
            End If
        Loop
    End Sub
    Public Function PlayerNameInput(ByVal playerName As String) As Boolean 'false if new player, true if existing
        Dim connectString As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=BattleshipDB.accdb"
        Dim sqlStringCheck As String = "SELECT * FROM BattleshipDB WHERE PlayerName = ?"
        Dim sqlStringAdd As String = "INSERT INTO BattleshipDB (PlayerName, Score, Wins, Losses) " & "VALUES (?, 18, 0, 0)"
        Dim dbConnection As New OleDbConnection()
        dbConnection.ConnectionString = connectString
        Dim checkExisting As New OleDbCommand(sqlStringCheck, dbConnection)
        Dim addNewPlayer As New OleDbCommand(sqlStringAdd, dbConnection)
        Dim thisDataReader As OleDbDataReader
        Dim playerNameParam As New OleDbParameter("@PlayerName", playerName)
        checkExisting.Parameters.AddWithValue("@PlayerName", playerName)
        addNewPlayer.Parameters.AddWithValue("@PlayerName", playerName)
        Dim results As New List(Of String)

        Try
            dbConnection.Open()
            thisDataReader = checkExisting.ExecuteReader()

            Do While thisDataReader.Read()
                Dim playerID As String = thisDataReader("ID").ToString
                Dim thisPlayerName As String = thisDataReader("PlayerName").ToString
                Dim wins As Integer = thisDataReader("Wins")
                Dim losses As Integer = thisDataReader("Losses")
                results.Add(playerID) 'index 0
                results.Add(thisPlayerName) '1
                results.Add(wins) '2
                results.Add(losses) '3
            Loop

            If results.Count = 0 Then
                MsgBox("New Player")
                addNewPlayer.ExecuteNonQuery()
            Else
                If Me.CurrentGame.CurrentPlayerTurn = 1 Then
                    MsgBox("Welcome back " & results(1).ToString)
                    Me.CurrentGame.Player1Name = results(1).ToString
                    Me.CurrentGame.Player1Wins = results(2)
                    Me.CurrentGame.Player1Losses = results(3)
                Else
                    Me.CurrentGame.Player2Name = results(1).ToString
                    MsgBox("Welcome back " & results(1).ToString)
                    Me.CurrentGame.Player2Wins = results(2)
                    Me.CurrentGame.Player2Losses = results(3)
                End If

            End If

        Catch ex As OleDbException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.GetType.ToString)
        Catch ex As SystemException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Finally
            dbConnection.Close()
        End Try

        Return Nothing
    End Function
    Public Sub GameOver()
        RaiseEvent SetNames()
        If Me.CurrentGame.NumPlayers = 1 Then
            GameOverPlayer1()
        ElseIf Me.CurrentGame.NumPlayers = 2 Then
            GameOverPlayer1()
            GameOverPlayer2()
        Else
            MsgBox("Error! Invalid number of players")
        End If
        RaiseEvent DisableInteractivity()
        RaiseEvent EndGameEvent()
        RaiseEvent ClearPB()
    End Sub
    Public Sub GameOverPlayer1()
        Dim connectString As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=BattleshipDB.accdb"
        Dim sqlStringUpdate As String = "UPDATE BattleshipDB SET Wins=?, Losses=? WHERE PlayerName=?"
        Dim dbConnection As New OleDbConnection()
        dbConnection.ConnectionString = connectString
        Dim updatePlayers As New OleDbCommand(sqlStringUpdate, dbConnection)
        Dim playerNameParam As New OleDbParameter("@Wins1", Me.CurrentGame.Player1Wins)
        updatePlayers.Parameters.AddWithValue("@Wins1", Me.CurrentGame.Player1Wins)
        Dim playerNameParam1 As New OleDbParameter("@Losses1", Me.CurrentGame.Player1Losses)
        updatePlayers.Parameters.AddWithValue("@Losses1", Me.CurrentGame.Player1Losses)
        Dim playerNameParam2 As New OleDbParameter("@Player1Name", CurrentGame.Player1Name)
        updatePlayers.Parameters.AddWithValue("@Player1Name", CurrentGame.Player1Name)
        Try
            dbConnection.Open()
            updatePlayers.ExecuteNonQuery()
        Catch ex As OleDbException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.GetType.ToString)
        Catch ex As SystemException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Finally
            dbConnection.Close()
            updatePlayers.Parameters.Clear()
        End Try
    End Sub
    Public Sub GameOverPlayer2()
        Dim connectString As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=BattleshipDB.accdb"
        Dim sqlStringUpdate As String = "UPDATE BattleshipDB SET Wins=?, Losses=? WHERE PlayerName=?"
        Dim dbConnection As New OleDbConnection()
        dbConnection.ConnectionString = connectString
        Dim updatePlayers2 As New OleDbCommand(sqlStringUpdate, dbConnection)
        Dim playerNameParam As New OleDbParameter("@Wins", Me.CurrentGame.Player2Wins)
        updatePlayers2.Parameters.AddWithValue("@Wins", Me.CurrentGame.Player2Wins)
        Dim playerNameParam1 As New OleDbParameter("@Losses", Me.CurrentGame.Player2Losses)
        updatePlayers2.Parameters.AddWithValue("@Losses", Me.CurrentGame.Player2Losses)
        Dim playerNameParam2 As New OleDbParameter("@Player2Name", CurrentGame.Player2Name)
        updatePlayers2.Parameters.AddWithValue("@Player2Name", CurrentGame.Player2Name)
        Try
            dbConnection.Open()
            updatePlayers2.ExecuteNonQuery()
        Catch ex As OleDbException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.GetType.ToString)
        Catch ex As SystemException
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StackTrace, ex.GetType.ToString)
        Finally
            dbConnection.Close()
        End Try
    End Sub
End Class
